<template>
  <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px">
    <el-form-item label="用户昵称" prop="nickName">
      <el-input v-model="ruleForm.nickName" autocomplete="off" placeholder="请输入用户昵称" />
    </el-form-item>

    <el-form-item label="手机号码" prop="mobile">
      <el-input v-model="ruleForm.mobile" autocomplete="off" placeholder="请输入手机号码" />
    </el-form-item>

    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email" autocomplete="off" placeholder="请输入邮箱" />
    </el-form-item>

    <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="ruleForm.sex">
        <el-radio :label="1">男</el-radio>
        <el-radio :label="0">女</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submit('ruleForm')">提交</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { validMobile, validEmail } from '@/utils/validate'

export default {
  props: {
    ruleForm: {
      type: Object,
      default: () => {
        return {
          nickName: '',
          mobile: '',
          email: '',
          sex: 0
        }
      }
    }
  },
  data() {
    var validateMobile = (rule, value, callback) => {
      if (!(validMobile(value))) {
        callback(new Error('请输入正确手机号码！'))
      } else {
        callback()
      }
    }

    var validateEmail = (rule, value, callback) => {
      if (!(validEmail(value))) {
        callback(new Error('请输入正确邮箱号码！'))
      } else {
        callback()
      }
    }

    return {
      rules: {
        nickName: [
          { required: true, trigger: 'blur', message: '请输入用户昵称' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, trigger: 'blur', message: '请输入手机号码' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, trigger: 'blur', message: '请输入邮箱' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        sex: [
          { required: true, trigger: 'blur', message: '请输选择性别' }
        ]
      }
    }
  },
  methods: {
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          console.log('数据校验失败!!')
          return false
        }
        console.log('数据验证成功')
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
